package com.brsya.autonat.ui;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.brsya.autonat.R;
import com.brsya.autonat.bean.BluetoothBean;
import com.brsya.autonat.constant.Constant;
import com.brsya.autonat.util.UiUtil;
import com.brsya.autonat.util.recycler.BaseAdapter;
import com.brsya.autonat.util.recycler.BaseViewHolder;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by Brsya
 * CreateDate: 2023/2/11  20:34
 * Description:
 * 选择蓝牙
 */
public class SelectBluetoothActivity extends AppCompatActivity {


    private View state;
    private RecyclerView rvBluetoothList;

    private BaseAdapter<BluetoothBean> adapter;
    private Button btnSelect;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_bluetooth);
        initView();

        initViewData();

        getDataList();
    }

    private void initView() {
        state = findViewById(R.id.state);
        rvBluetoothList = findViewById(R.id.rv_bluetooth_list);
        btnSelect = findViewById(R.id.btn_select);
    }

    private void initViewData() {
        UiUtil.setStatusPadding(this, state);
        rvBluetoothList.setLayoutManager(new LinearLayoutManager(this));

        rvBluetoothList.setAdapter(adapter = new BaseAdapter<BluetoothBean>() {
            @Override
            public BaseViewHolder onCreate(ViewGroup parent, int viewType) {
                View itemView = LayoutInflater.from(SelectBluetoothActivity.this).inflate(R.layout.item_bluetooth, parent, false);
                return new BaseViewHolder(itemView);
            }

            @Override
            public void onBind(BaseViewHolder viewHolder, int RealPosition, BluetoothBean data) {
                TextView tvValue = viewHolder.findViewById(R.id.tv_value);

                tvValue.setText(String.format("%s(%s)", data.getName(), data.getAddress()));

                if (data.isSelect()) {
                    tvValue.setBackgroundColor(0xFF34424d);
                } else {
                    tvValue.setBackgroundColor(0x00000000);
                }
            }

        });

        adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener<BluetoothBean>() {
            @Override
            public void onItemClick(int position, BluetoothBean data) {
                for (int i = 0; i < adapter.getDataList().size(); i++) {
                    adapter.getDataList().get(i).setSelect(i == position);
                    adapter.notifyItemChanged(i);
                }
                btnSelect.setEnabled(true);
            }
        });

        btnSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (BluetoothBean bluetoothBean : adapter.getDataList()) {
                    if (bluetoothBean.isSelect()) {
                        Intent intent = new Intent();
                        intent.putExtra(Constant.KEY_BLUETOOTH_NAME, bluetoothBean.getName());
                        intent.putExtra(Constant.KEY_BLUETOOTH_ADDRESS, bluetoothBean.getAddress());
                        setResult(RESULT_OK, intent);
                        finish();
                        return;
                    }
                }
            }
        });
    }


    private void getDataList() {
        List<BluetoothBean> dataList = getConnectedDevicesV2();
        adapter.setDataList(dataList);
    }


    /**
     * 获取系统中已连接的蓝牙设备
     *
     * @return
     */
    public List<BluetoothBean> getConnectedDevicesV2() {

        List<BluetoothBean> result = new ArrayList<>();
        Set<BluetoothDevice> deviceSet = new HashSet<>();

        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        //获取BLE的设备, profile只能是GATT或者GATT_SERVER
        //        List<BluetoothDevice> GattDevices = bluetoothManager.getConnectedDevices(BluetoothProfile.GATT);
        //        if (GattDevices!=null && GattDevices.size()>0){
        //            deviceSet.addAll(GattDevices);
        //        }
        //获取已配对的设备
        Set<BluetoothDevice> ClassicDevices = bluetoothManager.getAdapter().getBondedDevices();
        if (ClassicDevices != null && ClassicDevices.size() > 0) {
            deviceSet.addAll(ClassicDevices);
        }

        for (BluetoothDevice dev : deviceSet) {
            String Type = "";
            switch (dev.getType()) {
                case BluetoothDevice.DEVICE_TYPE_CLASSIC:
                    Type = "经典";
                    break;
                case BluetoothDevice.DEVICE_TYPE_LE:
                    Type = "BLE";
                    break;
                case BluetoothDevice.DEVICE_TYPE_DUAL:
                    Type = "双模";
                    break;
                default:
                    Type = "未知";
                    break;
            }
            Log.d("zbh", "address = " + dev.getAddress() + "(" + Type + "), name --> " + dev.getName());

            BluetoothBean bean = new BluetoothBean();
            bean.setType(dev.getType());
            bean.setTypeName(Type);
            bean.setName(dev.getName());
            bean.setAddress(dev.getAddress());

            result.add(bean);
        }
        return result;
    }
}
